<?php
/**
 * Created by PhpStorm.
 * Script Name: TemplateMsg.php
 * Create: 2023/1/11 18:29
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\queue;

use app\common\service\Queue;
use plugin\wechat\app\service\Mp as MpService;
use plugin\wechat\app\model\MpTemplatemsgTask;
use plugin\wechat\app\service\MpTemplateMsg as MsgService;

class TemplateMsg
{
    private $taskM;

    public function __construct()
    {
        $this->taskM = new MpTemplatemsgTask();
    }

    /**
     * 发送消息
     * @param $data
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function send($data)
    {
        $mp_info = $data['mp_info'];
        $task = $data['task'];
        $app = MpService::getApp($mp_info);
        $api = $app->template_message;
        //$api = $app->user; //测试
        $to = $data['to'];
        $url = str_replace(['{appid}', '{openid}'], [$mp_info['appid'], $to], $task['url']);
        //var_dump($to);
        $api->send([
            'touser' => $to,
            'template_id' => $task['template_id'],
            'url' => $url,
            'data' => json_decode($task['content'], true),
            'client_msg_id' => empty($data['client_msg_id']) ? 'dao_task_' . $task['id'] : $data['client_msg_id']
        ]);
    }

    /**
     * 拉取openid
     * @param array $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function pushTask($data = []){
        $task_id = $data['task_id'];
        if(! $task = MsgService::getTodoTask($task_id)){
            return true;
        }

        $mp_info = MsgService::getMpById($task['mp_id']);
        $app = MpService::getApp($mp_info);

        $task_update = [
            'id' => $task_id
        ];
        $task['status'] == 0 && $task_update['status'] = 1;

        $redis = wechat_redis();
        //openid入队列
        $pull_key = wechat_cache_key('openid_pull' . $task_id);
        $queue_key = wechat_cache_key('openid_queue' . $task_id);

        if($redis->get($pull_key) != 'end'){
            $next_openid = $redis->get($pull_key) ?: $task['next_openid'];
            //var_dump($next_openid);
            $res = $app->user->list($next_openid);
            if (!empty($res['count'])) {
                foreach ($res['data']['openid'] as $openid){
                    $redis->lpush($queue_key, $openid);
                }
                $redis->set($pull_key, $res['next_openid']);
            }else{
                //var_dump($res);
                $redis->set($pull_key, 'end');
            }
            var_dump('next openid:' . $redis->get($pull_key));
        }

        //消耗openid
        if($redis->llen($queue_key) > 0){
            $len = $task['speed'] * 10;
            $count = 1;

            while ($count <= $len && $openid = $redis->rpop($queue_key)){
                //发消息
                Queue::push([
                    'consumer' => ['\\plugin\\wechat\\app\\queue\\TemplateMsg', 'send'],
                    'task' => $task,
                    'mp_info' => $mp_info,
                    'to' => $openid
                ]);

                $task_update['count'] = $task['count'] + $count;
                $task_update['next_openid'] = $openid;

                $count++;
            }
        }else{
            $task_update['complete_time'] = time();
            $task_update['status'] = 2;
            $redis->del($pull_key);
            $redis->del($queue_key);
        }

        unset($openid_list, $app, $mp_info, $res, $task);
        MsgService::updateTask($task_update);

        //拉取下一份openid
        if(empty($task_update['status']) || $task_update['status'] != 2){
            Queue::push([
                'consumer' => ['\\plugin\\wechat\\app\\queue\\TemplateMsg', 'pushTask'],
                'task_id' => $task_id,
                'delay' => 10
            ]);
        }
    }

    public function pushTaskBak($data = []){
        $task_id = $data['task_id'];
        if(! $task = MsgService::getTodoTask($task_id)){
            return true;
        }

        $mp_info = MsgService::getMpById($task['mp_id']);
        $app = MpService::getApp($mp_info);

        $task_update = [
            'id' => $task_id
        ];
        $task['status'] == 0 && $task_update['status'] = 1;
        $res = $app->user->list($task['next_openid']);
        if (!empty($res['count'])) {
            $len = $task['speed'] * 10;
            $openid_list = array_slice($res['data']['openid'], 0, $len);
            foreach ($openid_list as $k => $v){
                //发消息
                Queue::push([
                    'consumer' => ['\\plugin\\wechat\\app\\queue\\TemplateMsg', 'send'],
                    'task' => $task,
                    'mp_info' => $mp_info,
                    'to' => $v
                ]);
            }
            $task_update['count'] = $task['count'] + count($openid_list);
            $task_update['next_openid'] = $openid_list[count($openid_list) - 1];
        }else{
            var_dump($res);
            $task_update['complete_time'] = time();
            $task_update['status'] = 2;
        }
        unset($openid_list, $app, $mp_info, $res, $task);
        MsgService::updateTask($task_update);

        //拉取下一份openid
        Queue::push([
            'consumer' => ['\\plugin\\wechat\\app\\queue\\TemplateMsg', 'pushTask'],
            'task_id' => $task_id,
            'delay' => 10
        ]);
    }
}